package blue.blog.pic;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Resource;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.blue.crawler.annotation.CrawlerConfig;
import com.blue.crawler.annotation.CrawlerPathConfig;
import com.blue.crawler.engine.ListDetailCrawl;

import blue.blog.core.model.CmsDoc;
import blue.blog.core.service.CmsDocService;
import blue.blog.util.CmsDocConvertor;

@Component
public class MzituCrawl implements ListDetailCrawl<MzituModel>
{
	private static Logger logger = LoggerFactory.getLogger(MzituCrawl.class);
	
	private static Pattern datePattern = Pattern.compile("/(\\d{4}/\\d{1,2}/\\d{1,2})");
	private static Pattern datePattern2 = Pattern.compile("/(\\d{4}\\d{1,2}\\d{1,2})");
	private static DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyyMMdd");
	private static DateTimeFormatter dateFormatter2 = DateTimeFormatter.ofPattern("yyyy/MM/dd");
	private static DateTimeFormatter dateFormatter3 = DateTimeFormatter.ofPattern("yyyy-MM-dd");
	
	@Resource
	private CmsDocService cmsDocService;
	
	public MzituCrawl()
	{
	}

	@Override
	public List<MzituModel> queryList(String html, CrawlerConfig config, CrawlerPathConfig pathConfig)
	{
		Document doc = Jsoup.parse(html);
		Elements liNodes = doc.select("#pins > li");
		List<MzituModel> list = new ArrayList<>();
		for (Element liNode : liNodes)
		{
			MzituModel model = new MzituModel();
			list.add(model);
			
			Element aNode = liNode.selectFirst("a");
			
			String url = aNode.attr("href").trim();
			model.setUrl(url);
			
			Element imgNode = aNode.select("img").first();
			if (imgNode != null)
			{
				String title = imgNode.attr("alt").trim();
				model.setTitle(title);
				
				String cover = imgNode.attr("data-original").trim();
				model.setCover(cover);
			}
			
			Element timeNode = liNode.selectFirst("span.time");
			if (timeNode != null)
			{
				String time = timeNode.text().trim();
				model.setCreateTime(LocalDate.parse(time, dateFormatter3).atStartOfDay());
			}
		}
		
		return list;
	}

	@Override
	public List<String> query(String html, CrawlerConfig config, CrawlerPathConfig pathConfig, MzituModel model)
	{
		Document doc = Jsoup.parse(html);
		List<String> picList = new ArrayList<>();
		Elements imgNodes = doc.select("div.main-image > p > a > img");
		if (imgNodes == null || imgNodes.isEmpty())
			return picList;
		
		StringBuilder content = new StringBuilder(64);
		for (Element imgNode : imgNodes)
		{
			String pic = imgNode.attr("src").trim();
			picList.add(pic);
			
			if (model.getCreateTime() == null)
			{
				Matcher m = datePattern2.matcher(pic);
				if (m.find())
				{
					String date = m.group(1);
					//System.out.println(date);
					model.setCreateTime(LocalDate.parse(date, dateFormatter).atStartOfDay());
				}
				else
				{
					m = datePattern.matcher(pic);
					if (m.find())
					{
						String date = m.group(1);
						System.out.println(date);
						model.setCreateTime(LocalDate.parse(date, dateFormatter2).atStartOfDay());
					}
					
				}
			}
			
			imgNode.removeAttr("alt");
			content.append(String.format("<p><img src=\"%s\" /></p>\n", pic));
		}
		model.setContent(content.toString());
		
		
		return picList;
	}

	@Override
	public List<String> queryPage(String html, CrawlerConfig config, CrawlerPathConfig pathConfig, MzituModel model, int page)
	{
		if (page > 1)
			return null;

		Document doc = Jsoup.parse(html);
		Elements aNodes = doc.select("div.pagenavi > a");
		List<String> pageList = new ArrayList<>();
		if (aNodes != null && aNodes.size() > 2)
		{
			String url = aNodes.get(aNodes.size() - 2).attr("href").trim();
			//System.out.println(url);
			
			int pos = url.lastIndexOf('/');
			String baseUrl = url.substring(0, pos);
			int max = Integer.parseInt(url.substring(pos+1));
			//System.out.println(baseUrl + "----" + max);
			
			for (int i = 2; i <=max; i++)
			{
				pageList.add(baseUrl + "/" + i);
			}
		}
		
		return pageList;
	}

	@Override
	public boolean existUrl(String url)
	{
		return cmsDocService.exist(url);
	}

	@Override
	public void handleModel(CrawlerConfig config, CrawlerPathConfig pathConfig, MzituModel model)
	{
		CmsDoc doc = CmsDocConvertor.toDoc(model, 1);
		logger.info("保存：{}", model.getTitle());
		cmsDocService.add(doc);
	}
}
